<%@ page import="java.net.URL" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>浩鲸知识库</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="shortcut icon" href="<%=basePath%>modules/micro/imgs/logo.ico">
    <!--页面布局，可忽略！-->
    <link href="<%=basePath%>frm/dynamic_menu/css/m-base.css" rel="stylesheet">
    <!--左侧导航样式-->
    <link href="<%=basePath%>frm/dynamic_menu/css/LeftNav.css" rel="stylesheet">

    <link href="<%=basePath%>frm/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="<%=basePath%>frm/bootstrap-3.3.7/css/bootstrap-treeview.css" rel="stylesheet">
    <link href="<%=basePath%>modules/micro/html/scrollcss.css" rel="stylesheet">
  </head>
  <body onload="getKnowlibCode();queryKnowLibList();">
    <div style="height:133px;position:relative;width:100%">
        <div class="panel-heading" style="background-size:auto;background:url(<%=basePath%>modules/micro/imgs/bgimg.jpg) no-repeat;color: #ffffff;margin:auto;width:100%">
          <div class="panel-title" style="display: inline">
            <a href="<%=basePath%>">
              <h1>浩鲸知识库</h1>
            </a>
          </div>
        </div>
        <ul class="nav nav-tabs nav-pills">
            <li class="dropdown">
              <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                知识库目录 <span class="caret"></span>
              </a>
              <ul class="dropdown-menu" id="knowLibUl">
                <%--<li><a href="#" onclick="queryInitData('all','changsha')">交管产品长沙团队</a></li>--%>
                <%--<li class="divider"></li>--%>
                <%--<li><a href="#" onclick="queryInitData('all','nanjing')">交管产品南京团队</a></li>--%>
                <%--<li class="divider"></li>--%>
                <%--<li><a href="#" onclick="queryInitData('all','ningbo')">交管产品宁波团队</a></li>--%>
              </ul>
          </li>
          <li ><a class="glyphicon glyphicon-plus" href="#" onclick="publishFunc()">发布</a></li>
          <li ><a class="glyphicon glyphicon-hand-right" href="#" onclick="replyFunc()">发布子主题</a></li>
          <li ><a class="glyphicon glyphicon-pencil" href="#" onclick="edit()">编辑</a></li>
          <li ><a class="glyphicon glyphicon-eye-open" href="#" onclick="lookFunc()">全屏预览</a></li>
          <li ><a class="glyphicon glyphicon-menu-hamburger" href="#" onclick="openNode()" id="treeOprate">展开</a></li>
          <li ><a class="glyphicon glyphicon-refresh" href="#" onclick="queryInitData('all')">刷新</a></li>
          <li ><a class="glyphicon glyphicon-user" href="#" onclick="loginPage()" id="knowTitle">登录</a></li>
          <li ><input id="searchID" style="margin-top: 3px;width: 150px;height: 34px;" placeholder="输入标题,回车搜索"/> </li>
          <!--
          <li ><a href="#">实名主题</a></li>
          <li ><a href="#">实名回复</a></li>
          <li ><a href="#" onclick="searchSubject()">搜索主题</a></li>

          <li class="dropdown">
            <a class="dropdown-toggle" data-toggle="dropdown" href="#">
              个人相关 <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
              <li><a href="#">修改密码</a></li>
              <li><a href="#">个人信息</a></li>
              <li class="divider"></li>
              <li><a href="#">我的主题</a></li>
            </ul>
          </li>
            -->
        </ul>
    </div>
    <div id="leftMenu" class="leftMenu" style="float: left;display: none;"></div>
    <div id="treeViewDiv" style="position:relative; height:100%; overflow:auto;">
      <div id="treeview" style="margin:auto;"/>
    </div>

    <%--<script src="<%=basePath%>frm/dynamic_menu/js/jquery.min.js" type="text/javascript"></script>--%>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/jquery.min.js"></script>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/bootstrap-treeview.js"></script>
    <script src="<%=basePath%>frm/layer/layer.js"></script>
    <script src="<%=basePath%>frm/dynamic_menu/js/LeftNav.js" type="text/javascript"></script>
    <!--<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>-->
  	<script type="text/javascript">
      var isOpen = false;
      // 预览弹出窗口 esc键退出
      $('body',document).on('keyup', function (e) {
          if (e.which === 27) {
              // console.log("按下esc");
              layer.closeAll();
          }
      });

      // 搜索框回车过来数据
      $('#searchID').keydown(function(event) {
          if (event.keyCode == 13) {
              var searchContent = $("#searchID").val();
              if (searchContent) {
                  queryInitData($('#searchID').val());
              } else {
                  queryInitData('all');
              }
          }
      });
      var selectedItem = {};
      var curScreemHeight = $(window).height() - 135;
      $("#treeViewDiv").height(curScreemHeight);
      $("#leftMenu").height(curScreemHeight);

      var tags = 0;

      function searchSubject() {
        var searchContent = $("#searchID").val();
        if (searchContent) {
            var expandibleNodes = $('#treeview').treeview('search', [ "[" + searchContent + "]", { ignoreCase: false, exactMatch: false } ]);
            //$('#treeview').treeview('selectNode', [ expandibleNodes, { silent: $('#chk-select-silent').is(':checked') }]);
//            if(!isOpen) {
//                ////展开指定节点
//                $('#treeview').treeview('expandNode', [ expandibleNodes, { levels: 0, silent: true}]);
//                isOpen = true;
//            } else {
//                $('#treeview').treeview('collapseNode', [ expandibleNodes, { silent: true }]);
//                isOpen = false;
//            }
            $('#treeview').treeview('expandAll', { silent: true });
        } else {
            layer.msg('请输入要搜索的标题内容!', {icon: 5});
        }
      }

      /**
       * 查询初始化主题数据
       */
      function queryInitData(condition, subjectCatName) {
          if (!subjectCatName) {
              subjectCatName = window.knowlibcode||"changsha";
          }
        //加载层-默认风格
        layer.load();
        $.post("<%=basePath%>subject/qryInitData.do", {condition: condition,subjectCatName:subjectCatName}, function result(data) {
          var rootData = [];
          var allData = JSON.parse(data);

          rootData = getTree(allData, "subjectId", "pSubjectId", "-1", condition);
          //if(allData) {
          //  for(var i=0;i<allData.length;) {
          //    var dataItem = allData[i];
          //    // 先加根节点
          //    if(Number(dataItem["pSubjectId"]) == -1) {
          //      rootData.push(dataItem);
          //      allData.splice(i, 1);
          //      i = 0;
          //      continue;
          //    }
          //    i++
          //  }
          //  // 遍历根节点 递归组装Tree结构树
            if(rootData) {
          //    for(var i=0;i<rootData.length;i++) {
          //      tags = 0;
          //      rootData[i] = searchChildren(allData,rootData[i]);
          //      if(tags != 0) {
          //        rootData[i].tags = [tags];
          //      } else {
          //        rootData[i].tags = [];
          //      }
//
          //    }

              var options = {
                color: "#428bca",
                expandIcon: 'glyphicon glyphicon-chevron-right',
                collapseIcon: 'glyphicon glyphicon-chevron-down',
                nodeIcon: 'glyphicon glyphicon-bookmark',
                //onhoverColor: "#86BF4B",
                borderColor: "red",
                showBorder: false,
                showTags: true,
                highlightSelected: true,
                selectedColor: "yellow",
                selectedBackColor: "darkorange",
                enableLinks: true,
                data: rootData
              };

              $('#treeview').treeview(options);
              layer.closeAll('loading');
              $('#treeview').on('nodeSelected', function(event, data) {
                selectedItem = data;
              });

              //节点取消选中时触发
              $('#treeview').on('nodeUnselected', function(event, data) {
                selectedItem = {};
              });
              // 收缩所有节点
              $('#treeview').treeview('collapseAll', { silent: false });

              //customDblClickFun();
//            }
          }
        });

        //$.ajax({
        //  data:"",//"name="+$("#name").val(),
        //  type:"POST",
        //  dataType: 'json',
        //  url:"/qryInitData.do",
        //  error:function(data){
        //    alert("出错了！！:"+data.msg);
        //  },
        //  success:function(data){
        //    alert("success:"+data);
        //    //$("#result").html(data.msg) ;
        //  }
        //});
      }

      function searchChildren(allData,rootDataItem) {
        var data = [];
        var nodes = [];
        for(var j=0;j<allData.length;) {
          // 根节点ID 查找所有的子节点
          if(rootDataItem["subjectId"] == allData[j]["pSubjectId"] && !allData[j].hasOwnProperty("nodes")) {

            var newNodeItem = searchChildren(allData,allData[j]);
            nodes.push(newNodeItem);
            //tags++;
            allData.splice(j, 1);
            j = 0;
            continue;
          }
          j++
        }
        rootDataItem.text = rootDataItem["subjectTitle"] + '  ['+rootDataItem['userName']+']';
        rootDataItem.href = rootDataItem["subjectLink"];

        if(nodes.length > 0) {
          tags += nodes.length;
          rootDataItem.nodes = nodes;
        }
        return rootDataItem;
      }

      function getTree(srcData, selfField, parentField, topFlag, condition) {
        var tree = new Array();
        if (srcData) {
          var dict = new Array();
          // add  roodnode
          var n = srcData.length;
          for (var i = 0; i < n; i++) {
            var item = srcData[i];
            var modifyUser = item["modifyUserName"] || '无数据';
            item.text = item["subjectTitle"] + "        【最后更新："+modifyUser + "】【更新时间：" + item["modifyDate"] +"】";// + '  ['+item['userName']+']';if
            item.href = "<%=basePath%>main.jsp?doc="+item["subjectId"]+"&menudp=open";
            if (item[parentField] === "no_catalog") {
                item.href = "<%=basePath%>main.jsp?doc="+item["subjectId"];
            }

            dict[item[selfField]] = item;
            if (item[parentField] == topFlag || item[parentField] == "" || condition != 'all') {
              tree[tree.length] = item; // 添加根节点
            }
          }
          // 由下至上，构造树
          for (var j = 0; j < n; j++) {
            //var tags = 0;
            var child = srcData[j];
            if (child[parentField] == topFlag || child[parentField] == "") {
              continue;
            }
            var parent = dict[child[parentField]];
            //parent.tags = [tags];
            if (parent) {
              //child.parent = parent;
              if (!parent.nodes) {
                parent.nodes = new Array();
              }
              //tags += parent.nodes.length;
              parent.nodes[parent.nodes.length] = child;
            }
          }
          return tree;
        }
      }

      /**
      * 匿名回复需要带当前选中的条目ID
       */
      function replyFunc() {
        if (isLogin()) {
            if(selectedItem.hasOwnProperty("subjectId")) {
                window.location.href="<%=basePath%>modules/micro/html/anonymouReplySubject.jsp?flag=add&subjectId=" + selectedItem["subjectId"];
            } else {
                //alert("请选中您要回复的主题!");
                //layer.alert("请选中您要回复的主题!");
                layer.msg('请先选择父节点!', {icon: 5});
            }
        }
      }

      /**
       * 发布
       * */
      function publishFunc() {
          if (isLogin()) {
              window.location.href="<%=basePath%>modules/micro/html/anonymouPubSubject.jsp";
          }
      }

      /**
       * 匿名编辑当前条目
       */
      function edit() {
          if (isLogin()) {
              // 已登陆且选中了菜单
              if(selectedItem["subjectId"]) {
                  window.location.href="<%=basePath%>modules/micro/html/anonymouReplySubject.jsp?flag=edit&subjectId=" + selectedItem["subjectId"];
              } else {
                  layer.msg('请选择要编辑的条目!', {icon: 5});
              }
          }
      }

      /**
       * 从cookie中获取用户信息
       * */
      function isLogin() {
          // 如果未登陆给出提示
          var hasCook = false;
          var cookieVue = document.cookie;
          var cookieArr = decodeURI(cookieVue).split(";");
          if (cookieArr) {
              for (var i=0;i<cookieArr.length;i++) {
                  if (cookieArr[i].indexOf("username") != -1) {
                      var uname = cookieArr[i].split("=");
                      hasCook = true;
                      window.userName = uname[1];
                  }
                  if (cookieArr[i].indexOf("knowlibcode") != -1) {
                      var knowlibcode = cookieArr[i].split("=");
                      window.knowlibcode = knowlibcode[1] || "changsha";
                  }
              }
              if (!hasCook) {
                  window.knowlibcode = "changsha";
                  layer.confirm('未登陆，不可编辑，是否跳转登陆页面?', {icon: 3, title:'提示'}, function(){
                      var sourceUrl = window.location.href;
                      window.location.href="<%=basePath%>modules/micro/login/login.jsp?sourceUrl=" + sourceUrl;
                  });
              }
          }
          return hasCook;
      }

      /**
       * 从缓存中获取知识库
       * */
      function getKnowlibCode() {
          var cookieVue = document.cookie;
          var cookieArr = decodeURI(cookieVue).split(";");
          if (cookieArr) {
              for (var i=0;i<cookieArr.length;i++) {
                  if (cookieArr[i].indexOf("username") != -1) {
                      var uname = cookieArr[i].split("=");
                      window.userName = uname[1];
                      $("#knowTitle").html(window.userName);
                  }
                  if (cookieArr[i].indexOf("knowlibcode") != -1) {
                      var knowlibcode = cookieArr[i].split("=");
                      window.knowlibcode = knowlibcode[1] || "changsha";
                  }
              }
          }

          queryInitData('all', window.knowlibcode);
      }

      /**
       * 预览
       */
      function lookFunc() {
        if(selectedItem.hasOwnProperty("subjectId")) {
          layer.open({
            type: 2,
            title: [selectedItem.subjectTitle,'font-size:18px;color:blue;'],
            //title:['快速浏览'],
            shadeClose: true,//点击遮罩关闭层
            shade: 0.8,
            area: ['100%', '100%'],
            move: false,
            content: "<%=basePath%>modules/micro/html/subjectLookDetail.jsp?subjectId=" + selectedItem["subjectId"] //iframe的url
            ,scrollbar: false
          });

        } else {
          //alert("请选中您要回复的主题!");
          //layer.alert("请选中您要回复的主题!");
          layer.msg('请选中您要快速浏览的主题!', {icon: 5});
        }
      }

      /**
       * 展开/折叠所有节点
       */
      function openNode() {
          if(!isOpen) {
              ////展开指定节点
//              $('#treeview').treeview('expandNode', [ expandibleNodes, { levels: 0, silent: true}]);
              $('#treeview').treeview('expandAll', { silent: false });
              $('#treeOprate').html("折叠");
              isOpen = true;
          } else {
//              $('#treeview').treeview('collapseNode', [ expandibleNodes, { silent: true }]);
              $('#treeview').treeview('collapseAll', { silent: false });
              $('#treeOprate').html("展开");
              isOpen = false;
          }
      }

      /**
       * 显示菜单
       */
      function menuOprate() {
          $("#leftMenu").empty();
          var displayVue = $("#leftMenu").css("display");
          if (displayVue == 'block') {
              $("#leftMenu").css("display", "none");
          } else {
              $("#leftMenu").css("display", "block");
              //加载层-默认风格
              layer.load();
              $.post("<%=basePath%>subject/qryInitData.do", {condition: "all"}, function result(data) {
                  layer.closeAll('loading');
                  var allData = JSON.parse(data);

                  var menu = getMenuData(allData, "subjectId", "pSubjectId", "-1") || [];

                  var parentNode = {name: '',
                      level:'0',
                      haschildren: true,
                      url: '#',
                      isopen: true,
                      children: menu
                  }
                  $.leftNav(".leftMenu", parentNode);
              });
          }
      }

      function getMenuData(srcData, selfField, parentField, topFlag) {
          var tree = new Array();
          if (srcData) {
              var dict = new Array();
              // add  roodnode
              var n = srcData.length;
              for (var i = 0; i < n; i++) {
                  var item = srcData[i];
                  item.level = 1;
                  item.name = item["subjectTitle"];
                  item.url = "<%=basePath%>modules/micro/html/"+item["subjectLink"];
                  item.isopen = true;
                  item.haschildren = false;
                  item.children = '';
                  if (item[parentField]) {
                      item.haschildren = true;
                      item.isopen = false;
                  }
                  dict[item[selfField]] = item;
                  if (item[parentField] == topFlag || item[parentField] == "") {
                      tree[tree.length] = item; // 添加根节点
                  }
              }
              // 由下至上，构造树
              for (var j = 0; j < n; j++) {
                  //var tags = 0;
                  var child = srcData[j];
                  if (child[parentField] == topFlag || child[parentField] == "") {
                      continue;
                  }
                  child.level = 2;
                  var parent = dict[child[parentField]];
                  //parent.tags = [tags];
                  if (parent) {
                      //child.parent = parent;
                      if (!parent.children) {
                          parent.children = new Array();
                      }
                      //tags += parent.nodes.length;
                      parent.children[parent.children.length] = child;
                  }
              }
              return tree;
          }
      }

      /**
       * 跳转登录页面
       */
      function loginPage() {
          var sourceUrl = window.location.href;
          window.location.href="<%=basePath%>modules/micro/login/login.jsp";
      }

      /**
       * 查询知识库
       */
      function queryKnowLibList() {
          var _that = this;
          $.post("<%=basePath%>knowLib/queryKnowLibList.do", {}, function result(data) {
              data = JSON.parse(data);
              if (data) {
                  for (var i = 0; i < data.length; i++) {
                      var html
                      if (i == data.length -1) {
                          html = '<li><a id="'+data[i]["knowCode"]+'" href="#" onclick="queryInitData("all",'+ data[i]["knowCode"] +')">'+ data[i]["knowName"] +'</a></li>';
                      }
                      else {
                          html = '<li><a id="'+data[i]["knowCode"]+'" href="#" onclick="queryInitData("all",'+ data[i]["knowCode"] +')">'+ data[i]["knowName"] +'</a></li>' +
                                 '</li><li class="divider"></li>';
                      }
                      $(html).appendTo($("#knowLibUl"));
//                      $('#knowLibUl li a').on("click", queryInitData("all", data[i]["knowCode"]));
                      //触发通过js动态添加的超链接a
                      $('#knowLibUl li a').on("click", function(){
                          _that.queryInitData("all", this.id);
                      });
                  }
              }
          });
      }
  	</script>
  </body>
